home *** CD-ROM | disk | FTP | other *** search
/ Libris Britannia 4 / science library(b).zip / science library(b) / DJGPP / PAT202SR.ZIP / src / patch / patch.c < prev    next >
C/C++ Source or Header  |  1993-05-31  |  21KB  |  871 lines

  1. char rcsid[] =
  2.     "$Header: patch.c,v 2.0.2.0 90/05/01 22:17:50 davison Locked $";
  3.  
  4. /* patch - a program to apply diffs to original files
  5.  *
  6.  * Copyright 1986, Larry Wall
  7.  *
  8.  * This program may be copied as long as you don't try to make any
  9.  * money off of it, or pretend that you wrote it.
  10.  *
  11.  * $Log:    patch.c,v $
  12.  * Revision 2.0.2.0  90/05/01  22:17:50  davison
  13.  * patch12u: unidiff support added
  14.  * 
  15.  * Revision 2.0.1.6  88/06/22  20:46:39  lwall
  16.  * patch12: rindex() wasn't declared
  17.  * 
  18.  * Revision 2.0.1.5  88/06/03  15:09:37  lwall
  19.  * patch10: exit code improved.
  20.  * patch10: better support for non-flexfilenames.
  21.  * 
  22.  * Revision 2.0.1.4  87/02/16  14:00:04  lwall
  23.  * Short replacement caused spurious "Out of sync" message.
  24.  * 
  25.  * Revision 2.0.1.3  87/01/30  22:45:50  lwall
  26.  * Improved diagnostic on sync error.
  27.  * Moved do_ed_script() to pch.c.
  28.  * 
  29.  * Revision 2.0.1.2  86/11/21  09:39:15  lwall
  30.  * Fuzz factor caused offset of installed lines.
  31.  * 
  32.  * Revision 2.0.1.1  86/10/29  13:10:22  lwall
  33.  * Backwards search could terminate prematurely.
  34.  * 
  35.  * Revision 2.0  86/09/17  15:37:32  lwall
  36.  * Baseline for netwide release.
  37.  * 
  38.  * Revision 1.5  86/08/01  20:53:24  lwall
  39.  * Changed some %d's to %ld's.
  40.  * Linted.
  41.  * 
  42.  * Revision 1.4  86/08/01  19:17:29  lwall
  43.  * Fixes for machines that can't vararg.
  44.  * Added fuzz factor.
  45.  * Generalized -p.
  46.  * General cleanup.
  47.  * 
  48.  * 85/08/15 van%ucbmonet@berkeley
  49.  * Changes for 4.3bsd diff -c.
  50.  *
  51.  * Revision 1.3  85/03/26  15:07:43  lwall
  52.  * Frozen.
  53.  * 
  54.  * Revision 1.2.1.9  85/03/12  17:03:35  lwall
  55.  * Changed pfp->_file to fileno(pfp).
  56.  * 
  57.  * Revision 1.2.1.8  85/03/12  16:30:43  lwall
  58.  * Check i_ptr and i_womp to make sure they aren't null before freeing.
  59.  * Also allow ed output to be suppressed.
  60.  * 
  61.  * Revision 1.2.1.7  85/03/12  15:56:13  lwall
  62.  * Added -p option from jromine@uci-750a.
  63.  * 
  64.  * Revision 1.2.1.6  85/03/12  12:12:51  lwall
  65.  * Now checks for normalness of file to patch.
  66.  * 
  67.  * Revision 1.2.1.5  85/03/12  11:52:12  lwall
  68.  * Added -D (#ifdef) option from joe@fluke.
  69.  * 
  70.  * Revision 1.2.1.4  84/12/06  11:14:15  lwall
  71.  * Made smarter about SCCS subdirectories.
  72.  * 
  73.  * Revision 1.2.1.3  84/12/05  11:18:43  lwall
  74.  * Added -l switch to do loose string comparison.
  75.  * 
  76.  * Revision 1.2.1.2  84/12/04  09:47:13  lwall
  77.  * Failed hunk count not reset on multiple patch file.
  78.  * 
  79.  * Revision 1.2.1.1  84/12/04  09:42:37  lwall
  80.  * Branch for sdcrdcf changes.
  81.  * 
  82.  * Revision 1.2  84/11/29  13:29:51  lwall
  83.  * Linted.  Identifiers uniqified.  Fixed i_ptr malloc() bug.  Fixed
  84.  * multiple calls to mktemp().  Will now work on machines that can only
  85.  * read 32767 chars.  Added -R option for diffs with new and old swapped.
  86.  * Various cosmetic changes.
  87.  * 
  88.  * Revision 1.1  84/11/09  17:03:58  lwall
  89.  * Initial revision
  90.  * 
  91.  */
  92.  
  93. #include "INTERN.h"
  94. #include "common.h"
  95. #include "EXTERN.h"
  96. #include "version.h"
  97. #include "util.h"
  98. #include "pch.h"
  99. #include "inp.h"
  100.  
  101. /* procedures */
  102.  
  103. void reinitialize_almost_everything();
  104. void get_some_switches();
  105. LINENUM locate_hunk();
  106. void abort_hunk();
  107. void apply_hunk();
  108. void init_output();
  109. void init_reject();
  110. void copy_till();
  111. void spew_output();
  112. void dump_line();
  113. bool patch_match();
  114. bool similar();
  115. void re_input();
  116. void my_exit();
  117.  
  118. /* Nonzero if -R was specified on command line.  */
  119. static int reverse_flag_specified = FALSE;
  120.  
  121. /* Apply a set of diffs as appropriate. */
  122.  
  123. main(argc,argv)
  124. int argc;
  125. char **argv;
  126. {
  127.     LINENUM where;
  128.     LINENUM newwhere;
  129.     LINENUM fuzz;
  130.     LINENUM mymaxfuzz;
  131.     int hunk = 0;
  132.     int failed = 0;
  133.     int failtotal = 0;
  134.     int i;
  135.  
  136.     setbuf(stderr, serrbuf);
  137.     for (i = 0; i<MAXFILEC; i++)
  138.     filearg[i] = Nullch;
  139.  
  140.     /* Cons up the names of the temporary files.  */
  141.     {
  142.       /* Directory for temporary files.  */
  143.       char *tmpdir;
  144.       int tmpname_len;
  145.  
  146.       tmpdir = getenv ("TMPDIR");
  147.       if (tmpdir == NULL) {
  148.     tmpdir = "/tmp";
  149.       }
  150.       if (tmpdir[strlen(tmpdir)-1] == '/')
  151.         tmpdir[strlen(tmpdir)-1] = 0;
  152.       tmpname_len = strlen (tmpdir) + 20;
  153.  
  154.       TMPOUTNAME = (char *) malloc (tmpname_len);
  155.       strcpy (TMPOUTNAME, tmpdir);
  156.       strcat (TMPOUTNAME, "/poXXXXXX");
  157.       Mktemp(TMPOUTNAME);
  158.  
  159.       TMPINNAME = (char *) malloc (tmpname_len);
  160.       strcpy (TMPINNAME, tmpdir);
  161.       strcat (TMPINNAME, "/piXXXXXX");
  162.       Mktemp(TMPINNAME);
  163.  
  164.       TMPREJNAME = (char *) malloc (tmpname_len);
  165.       strcpy (TMPREJNAME, tmpdir);
  166.       strcat (TMPREJNAME, "/prXXXXXX");
  167.       Mktemp(TMPREJNAME);
  168.  
  169.       TMPPATNAME = (char *) malloc (tmpname_len);
  170.       strcpy (TMPPATNAME, tmpdir);
  171.       strcat (TMPPATNAME, "/ppXXXXXX");
  172.       Mktemp(TMPPATNAME);
  173.     }
  174.  
  175.     /* parse switches */
  176.     Argc = argc;
  177.     Argv = argv;
  178.     get_some_switches();
  179.     
  180.     /* make sure we clean up /tmp in case of disaster */
  181.     set_signals(0);
  182.  
  183.     for (
  184.     open_patch_file(filearg[1]);
  185.     there_is_another_patch();
  186.     reinitialize_almost_everything()
  187.     ) {                    /* for each patch in patch file */
  188.  
  189.     if (outname == Nullch)
  190.         outname = savestr(filearg[0]);
  191.     
  192.     /* initialize the patched file */
  193.     if (!skip_rest_of_patch)
  194.         init_output(TMPOUTNAME);
  195.     
  196.     /* for ed script just up and do it and exit */
  197.     if (diff_type == ED_DIFF) {
  198.         do_ed_script();
  199.         continue;
  200.     }
  201.     
  202.     /* initialize reject file */
  203.     init_reject(TMPREJNAME);
  204.     
  205.     /* find out where all the lines are */
  206.     if (!skip_rest_of_patch)
  207.         scan_input(filearg[0]);
  208.     
  209.     /* from here on, open no standard i/o files, because malloc */
  210.     /* might misfire and we can't catch it easily */
  211.     
  212.     /* apply each hunk of patch */
  213.     hunk = 0;
  214.     failed = 0;
  215.     out_of_mem = FALSE;
  216.     while (another_hunk()) {
  217.         hunk++;
  218.         fuzz = Nulline;
  219.         mymaxfuzz = pch_context();
  220.         if (maxfuzz < mymaxfuzz)
  221.         mymaxfuzz = maxfuzz;
  222.         if (!skip_rest_of_patch) {
  223.         do {
  224.             where = locate_hunk(fuzz);
  225.             if (hunk == 1 && where == Nulline && !force) {
  226.                         /* dwim for reversed patch? */
  227.             if (!pch_swap()) {
  228.                 if (fuzz == Nulline)
  229.                 say1(
  230. "Not enough memory to try swapped hunk!  Assuming unswapped.\n");
  231.                 continue;
  232.             }
  233.             reverse = !reverse;
  234.             where = locate_hunk(fuzz);  /* try again */
  235.             if (where == Nulline) {        /* didn't find it swapped */
  236.                 if (!pch_swap())         /* put it back to normal */
  237.                 fatal1("Lost hunk on alloc error!\n");
  238.                 reverse = !reverse;
  239.             }
  240.             else if (noreverse) {
  241.                 if (!pch_swap())         /* put it back to normal */
  242.                 fatal1("Lost hunk on alloc error!\n");
  243.                 reverse = !reverse;
  244.                 say1(
  245. "Ignoring previously applied (or reversed) patch.\n");
  246.                 skip_rest_of_patch = TRUE;
  247.             }
  248.             else {
  249.                 ask3(
  250. "%seversed (or previously applied) patch detected!  %s -R? [y] ",
  251.                 reverse ? "R" : "Unr",
  252.                 reverse ? "Assume" : "Ignore");
  253.                 if (*buf == 'n') {
  254.                 ask1("Apply anyway? [n] ");
  255.                 if (*buf != 'y')
  256.                     skip_rest_of_patch = TRUE;
  257.                 where = Nulline;
  258.                 reverse = !reverse;
  259.                 if (!pch_swap())  /* put it back to normal */
  260.                     fatal1("Lost hunk on alloc error!\n");
  261.                 }
  262.             }
  263.             }
  264.         } while (!skip_rest_of_patch && where == Nulline &&
  265.             ++fuzz <= mymaxfuzz);
  266.  
  267.         if (skip_rest_of_patch) {        /* just got decided */
  268.             Fclose(ofp);
  269.             ofp = Nullfp;
  270.         }
  271.         }
  272.  
  273.         newwhere = pch_newfirst() + last_offset;
  274.         if (skip_rest_of_patch) {
  275.         abort_hunk();
  276.         failed++;
  277.         if (verbose)
  278.             say3("Hunk #%d ignored at %ld.\n", hunk, newwhere);
  279.         }
  280.         else if (where == Nulline) {
  281.         abort_hunk();
  282.         failed++;
  283.         if (verbose)
  284.             say3("Hunk #%d failed at %ld.\n", hunk, newwhere);
  285.         }
  286.         else {
  287.         apply_hunk(where);
  288.         if (verbose) {
  289.             say3("Hunk #%d succeeded at %ld", hunk, newwhere);
  290.             if (fuzz)
  291.             say2(" with fuzz %ld", fuzz);
  292.             if (last_offset)
  293.             say3(" (offset %ld line%s)",
  294.                 last_offset, last_offset==1L?"":"s");
  295.             say1(".\n");
  296.         }
  297.         }
  298.     }
  299.  
  300.     if (out_of_mem && using_plan_a) {
  301.         Argc = Argc_last;
  302.         Argv = Argv_last;
  303.         say1("\n\nRan out of memory using Plan A--trying again...\n\n");
  304.         continue;
  305.     }
  306.     
  307.     assert(hunk);
  308.     
  309.     /* finish spewing out the new file */
  310.     if (!skip_rest_of_patch)
  311.         spew_output();
  312.     
  313.     /* and put the output where desired */
  314.     ignore_signals();
  315.     if (!skip_rest_of_patch) {
  316.         if (move_file(TMPOUTNAME, outname) < 0) {
  317.         toutkeep = TRUE;
  318.         chmod(TMPOUTNAME, filemode);
  319.         }
  320.         else
  321.         chmod(outname, filemode);
  322.     }
  323.     Fclose(rejfp);
  324.     rejfp = Nullfp;
  325.     if (failed) {
  326.         failtotal += failed;
  327.         if (!*rejname) {
  328.         Strcpy(rejname, outname);
  329. #ifndef FLEXFILENAMES
  330.         {
  331.             char *rindex();
  332.             char *s = rindex(rejname,'/');
  333.  
  334.             if (!s)
  335.             s = rejname;
  336.             if (strlen(s) > 13)
  337.             if (s[12] == '.')    /* try to preserve difference */
  338.                 s[12] = s[13];    /* between .h, .c, .y, etc. */
  339.             s[13] = '\0';
  340.         }
  341. #endif
  342.         Strcat(rejname, REJEXT);
  343.         }
  344.         if (skip_rest_of_patch) {
  345.         say4("%d out of %d hunks ignored--saving rejects to %s\n",
  346.             failed, hunk, rejname);
  347.         }
  348.         else {
  349.         say4("%d out of %d hunks failed--saving rejects to %s\n",
  350.             failed, hunk, rejname);
  351.         }
  352.         if (move_file(TMPREJNAME, rejname) < 0)
  353.         trejkeep = TRUE;
  354.     }
  355.     set_signals(1);
  356.     }
  357.     my_exit(failtotal);
  358. }
  359.  
  360. /* Prepare to find the next patch to do in the patch file. */
  361.  
  362. void
  363. reinitialize_almost_everything()
  364. {
  365.     re_patch();
  366.     re_input();
  367.  
  368.     input_lines = 0;
  369.     last_frozen_line = 0;
  370.  
  371.     filec = 0;
  372.     if (filearg[0] != Nullch && !out_of_mem) {
  373.     free(filearg[0]);
  374.     filearg[0] = Nullch;
  375.     }
  376.  
  377.     if (outname != Nullch) {
  378.     free(outname);
  379.     outname = Nullch;
  380.     }
  381.  
  382.     last_offset = 0;
  383.  
  384.     diff_type = 0;
  385.  
  386.     if (revision != Nullch) {
  387.     free(revision);
  388.     revision = Nullch;
  389.     }
  390.  
  391.     reverse = reverse_flag_specified;
  392.     skip_rest_of_patch = FALSE;
  393.  
  394.     get_some_switches();
  395.  
  396.     if (filec >= 2)
  397.     fatal1("You may not change to a different patch file.\n");
  398. }
  399.  
  400. static char *
  401. nextarg()
  402. {
  403.     if (!--Argc)
  404.     fatal2("patch: missing argument after `%s'\n", *Argv);
  405.     return *++Argv;
  406. }
  407.  
  408. /* Process switches and filenames up to next '+' or end of list. */
  409.  
  410. void
  411. get_some_switches()
  412. {
  413.     Reg1 char *s;
  414.  
  415.     rejname[0] = '\0';
  416.     Argc_last = Argc;
  417.     Argv_last = Argv;
  418.     if (!Argc)
  419.     return;
  420.     for (Argc--,Argv++; Argc; Argc--,Argv++) {
  421.     s = Argv[0];
  422.     if (strEQ(s, "+")) {
  423.         return;            /* + will be skipped by for loop */
  424.     }
  425.     if (*s != '-' || !s[1]) {
  426.         if (filec == MAXFILEC)
  427.         fatal1("patch: Too many file arguments.\n");
  428.         filearg[filec++] = savestr(s);
  429.     }
  430.     else {
  431.         switch (*++s) {
  432.         case 'b':
  433.         origext = savestr(nextarg());
  434.         break;
  435.         case 'B':
  436.         origprae = savestr(nextarg());
  437.         break;
  438.         case 'c':
  439.         diff_type = CONTEXT_DIFF;
  440.         break;
  441.         case 'd':
  442.         if (!*++s)
  443.             s = nextarg();
  444.         if (chdir(s) < 0)
  445.             fatal2("Can't cd to %s.\n", s);
  446.         break;
  447.         case 'D':
  448.             do_defines = TRUE;
  449.         if (!*++s)
  450.             s = nextarg();
  451.         if (!isalpha(*s) && '_' != *s)
  452.             fatal1("Argument to -D not an identifier.\n");
  453.         Sprintf(if_defined, "#ifdef %s\n", s);
  454.         Sprintf(not_defined, "#ifndef %s\n", s);
  455.         Sprintf(end_defined, "#endif /* %s */\n", s);
  456.         break;
  457.         case 'e':
  458.         diff_type = ED_DIFF;
  459.         break;
  460.         case 'f':
  461.         force = TRUE;
  462.         break;
  463.         case 'F':
  464.         if (*++s == '=')
  465.             s++;
  466.         maxfuzz = atoi(s);
  467.         break;
  468.         case 'l':
  469.         canonicalize = TRUE;
  470.         break;
  471.         case 'n':
  472.         diff_type = NORMAL_DIFF;
  473.         break;
  474.         case 'N':
  475.         noreverse = TRUE;
  476.         break;
  477.         case 'o':
  478.         outname = savestr(nextarg());
  479.         break;
  480.         case 'p':
  481.         if (*++s == '=')
  482.             s++;
  483.         strippath = atoi(s);
  484.         break;
  485.         case 'r':
  486.         Strcpy(rejname, nextarg());
  487.         break;
  488.         case 'R':
  489.         reverse = TRUE;
  490.         reverse_flag_specified = TRUE;
  491.         break;
  492.         case 's':
  493.         verbose = FALSE;
  494.         break;
  495.         case 'S':
  496.         skip_rest_of_patch = TRUE;
  497.         break;
  498.         case 'u':
  499.         diff_type = UNI_DIFF;
  500.         break;
  501.         case 'v':
  502.         version();
  503.         break;
  504. #ifdef DEBUGGING
  505.         case 'x':
  506.         debug = atoi(s+1);
  507.         break;
  508. #endif
  509.         default:
  510.         fprintf(stderr, "patch: unrecognized option `%s'\n", Argv[0]);
  511.         fprintf(stderr, "\
  512. Usage: patch [-ceflnNRsSuv] [-b backup-ext] [-B backup-prefix] [-d directory]\n\
  513.        [-D symbol] [-Fmax-fuzz] [-o out-file] [-p[strip-count]]\n\
  514.        [-r rej-name] [origfile] [patchfile] [[+] [options] [origfile]...]\n\
  515. ");
  516.         my_exit(1);
  517.         }
  518.     }
  519.     }
  520. }
  521.  
  522. /* Attempt to find the right place to apply this hunk of patch. */
  523.  
  524. LINENUM
  525. locate_hunk(fuzz)
  526. LINENUM fuzz;
  527. {
  528.     Reg1 LINENUM first_guess = pch_first() + last_offset;
  529.     Reg2 LINENUM offset;
  530.     LINENUM pat_lines = pch_ptrn_lines();
  531.     Reg3 LINENUM max_pos_offset = input_lines - first_guess
  532.                 - pat_lines + 1; 
  533.     Reg4 LINENUM max_neg_offset = first_guess - last_frozen_line - 1
  534.                 + pch_context();
  535.  
  536.     if (!pat_lines)            /* null range matches always */
  537.     return first_guess;
  538.     if (max_neg_offset >= first_guess)    /* do not try lines < 0 */
  539.     max_neg_offset = first_guess - 1;
  540.     if (first_guess <= input_lines && patch_match(first_guess, Nulline, fuzz))
  541.     return first_guess;
  542.     for (offset = 1; ; offset++) {
  543.     Reg5 bool check_after = (offset <= max_pos_offset);
  544.     Reg6 bool check_before = (offset <= max_neg_offset);
  545.  
  546.     if (check_after && patch_match(first_guess, offset, fuzz)) {
  547. #ifdef DEBUGGING
  548.         if (debug & 1)
  549.         say3("Offset changing from %ld to %ld\n", last_offset, offset);
  550. #endif
  551.         last_offset = offset;
  552.         return first_guess+offset;
  553.     }
  554.     else if (check_before && patch_match(first_guess, -offset, fuzz)) {
  555. #ifdef DEBUGGING
  556.         if (debug & 1)
  557.         say3("Offset changing from %ld to %ld\n", last_offset, -offset);
  558. #endif
  559.         last_offset = -offset;
  560.         return first_guess-offset;
  561.     }
  562.     else if (!check_before && !check_after)
  563.         return Nulline;
  564.     }
  565. }
  566.  
  567. /* We did not find the pattern, dump out the hunk so they can handle it. */
  568.  
  569. void
  570. abort_hunk()
  571. {
  572.     Reg1 LINENUM i;
  573.     Reg2 LINENUM pat_end = pch_end();
  574.     /* add in last_offset to guess the same as the previous successful hunk */
  575.     LINENUM oldfirst = pch_first() + last_offset;
  576.     LINENUM newfirst = pch_newfirst() + last_offset;
  577.     LINENUM oldlast = oldfirst + pch_ptrn_lines() - 1;
  578.     LINENUM newlast = newfirst + pch_repl_lines() - 1;
  579.     char *stars = (diff_type >= NEW_CONTEXT_DIFF ? " ****" : "");
  580.     char *minuses = (diff_type >= NEW_CONTEXT_DIFF ? " ----" : " -----");
  581.  
  582.     fprintf(rejfp, "***************\n");
  583.     for (i=0; i<=pat_end; i++) {
  584.     switch (pch_char(i)) {
  585.     case '*':
  586.         if (oldlast < oldfirst)
  587.         fprintf(rejfp, "*** 0%s\n", stars);
  588.         else if (oldlast == oldfirst)
  589.         fprintf(rejfp, "*** %ld%s\n", oldfirst, stars);
  590.         else
  591.         fprintf(rejfp, "*** %ld,%ld%s\n", oldfirst, oldlast, stars);
  592.         break;
  593.     case '=':
  594.         if (newlast < newfirst)
  595.         fprintf(rejfp, "--- 0%s\n", minuses);
  596.         else if (newlast == newfirst)
  597.         fprintf(rejfp, "--- %ld%s\n", newfirst, minuses);
  598.         else
  599.         fprintf(rejfp, "--- %ld,%ld%s\n", newfirst, newlast, minuses);
  600.         break;
  601.     case '\n':
  602.         fprintf(rejfp, "%s", pfetch(i));
  603.         break;
  604.     case ' ': case '-': case '+': case '!':
  605.         fprintf(rejfp, "%c %s", pch_char(i), pfetch(i));
  606.         break;
  607.     default:
  608.         say1("Fatal internal error in abort_hunk().\n"); 
  609.         abort();
  610.     }
  611.     }
  612. }
  613.  
  614. /* We found where to apply it (we hope), so do it. */
  615.  
  616. void
  617. apply_hunk(where)
  618. LINENUM where;
  619. {
  620.     Reg1 LINENUM old = 1;
  621.     Reg2 LINENUM lastline = pch_ptrn_lines();
  622.     Reg3 LINENUM new = lastline+1;
  623. #define OUTSIDE 0
  624. #define IN_IFNDEF 1
  625. #define IN_IFDEF 2
  626. #define IN_ELSE 3
  627.     Reg4 int def_state = OUTSIDE;
  628.     Reg5 bool R_do_defines = do_defines;
  629.     Reg6 LINENUM pat_end = pch_end();
  630.  
  631.     where--;
  632.     while (pch_char(new) == '=' || pch_char(new) == '\n')
  633.     new++;
  634.     
  635.     while (old <= lastline) {
  636.     if (pch_char(old) == '-') {
  637.         copy_till(where + old - 1);
  638.         if (R_do_defines) {
  639.         if (def_state == OUTSIDE) {
  640.             fputs(not_defined, ofp);
  641.             def_state = IN_IFNDEF;
  642.         }
  643.         else if (def_state == IN_IFDEF) {
  644.             fputs(else_defined, ofp);
  645.             def_state = IN_ELSE;
  646.         }
  647.         fputs(pfetch(old), ofp);
  648.         }
  649.         last_frozen_line++;
  650.         old++;
  651.     }
  652.     else if (new > pat_end) {
  653.         break;
  654.     }
  655.     else if (pch_char(new) == '+') {
  656.         copy_till(where + old - 1);
  657.         if (R_do_defines) {
  658.         if (def_state == IN_IFNDEF) {
  659.             fputs(else_defined, ofp);
  660.             def_state = IN_ELSE;
  661.         }
  662.         else if (def_state == OUTSIDE) {
  663.             fputs(if_defined, ofp);
  664.             def_state = IN_IFDEF;
  665.         }
  666.         }
  667.         fputs(pfetch(new), ofp);
  668.         new++;
  669.     }
  670.     else if (pch_char(new) != pch_char(old)) {
  671.         say3("Out-of-sync patch, lines %ld,%ld--mangled text or line numbers, maybe?\n",
  672.         pch_hunk_beg() + old,
  673.         pch_hunk_beg() + new);
  674. #ifdef DEBUGGING
  675.         say3("oldchar = '%c', newchar = '%c'\n",
  676.         pch_char(old), pch_char(new));
  677. #endif
  678.         my_exit(1);
  679.     }
  680.     else if (pch_char(new) == '!') {
  681.         copy_till(where + old - 1);
  682.         if (R_do_defines) {
  683.            fputs(not_defined, ofp);
  684.            def_state = IN_IFNDEF;
  685.         }
  686.         while (pch_char(old) == '!') {
  687.         if (R_do_defines) {
  688.             fputs(pfetch(old), ofp);
  689.         }
  690.         last_frozen_line++;
  691.         old++;
  692.         }
  693.         if (R_do_defines) {
  694.         fputs(else_defined, ofp);
  695.         def_state = IN_ELSE;
  696.         }
  697.         while (pch_char(new) == '!') {
  698.         fputs(pfetch(new), ofp);
  699.         new++;
  700.         }
  701.     }
  702.     else {
  703.         assert(pch_char(new) == ' ');
  704.         old++;
  705.         new++;
  706.         if (R_do_defines && def_state != OUTSIDE) {
  707.         fputs(end_defined, ofp);
  708.         def_state = OUTSIDE;
  709.         }
  710.     }
  711.     }
  712.     if (new <= pat_end && pch_char(new) == '+') {
  713.     copy_till(where + old - 1);
  714.     if (R_do_defines) {
  715.         if (def_state == OUTSIDE) {
  716.             fputs(if_defined, ofp);
  717.         def_state = IN_IFDEF;
  718.         }
  719.         else if (def_state == IN_IFNDEF) {
  720.         fputs(else_defined, ofp);
  721.         def_state = IN_ELSE;
  722.         }
  723.     }
  724.     while (new <= pat_end && pch_char(new) == '+') {
  725.         fputs(pfetch(new), ofp);
  726.         new++;
  727.     }
  728.     }
  729.     if (R_do_defines && def_state != OUTSIDE) {
  730.     fputs(end_defined, ofp);
  731.     }
  732. }
  733.  
  734. /* Open the new file. */
  735.  
  736. void
  737. init_output(name)
  738. char *name;
  739. {
  740.     ofp = fopen(name, "w");
  741.     if (ofp == Nullfp)
  742.     fatal2("patch: can't create %s.\n", name);
  743. }
  744.  
  745. /* Open a file to put hunks we can't locate. */
  746.  
  747. void
  748. init_reject(name)
  749. char *name;
  750. {
  751.     rejfp = fopen(name, "w");
  752.     if (rejfp == Nullfp)
  753.     fatal2("patch: can't create %s.\n", name);
  754. }
  755.  
  756. /* Copy input file to output, up to wherever hunk is to be applied. */
  757.  
  758. void
  759. copy_till(lastline)
  760. Reg1 LINENUM lastline;
  761. {
  762.     Reg2 LINENUM R_last_frozen_line = last_frozen_line;
  763.  
  764.     if (R_last_frozen_line > lastline)
  765.     say1("patch: misordered hunks! output will be garbled.\n");
  766.     while (R_last_frozen_line < lastline) {
  767.     dump_line(++R_last_frozen_line);
  768.     }
  769.     last_frozen_line = R_last_frozen_line;
  770. }
  771.  
  772. /* Finish copying the input file to the output file. */
  773.  
  774. void
  775. spew_output()
  776. {
  777. #ifdef DEBUGGING
  778.     if (debug & 256)
  779.     say3("il=%ld lfl=%ld\n",input_lines,last_frozen_line);
  780. #endif
  781.     if (input_lines)
  782.     copy_till(input_lines);        /* dump remainder of file */
  783.     Fclose(ofp);
  784.     ofp = Nullfp;
  785. }
  786.  
  787. /* Copy one line from input to output. */
  788.  
  789. void
  790. dump_line(line)
  791. LINENUM line;
  792. {
  793.     Reg1 char *s;
  794.     Reg2 char R_newline = '\n';
  795.  
  796.     /* Note: string is not null terminated. */
  797.     for (s=ifetch(line, 0); putc(*s, ofp) != R_newline; s++) ;
  798. }
  799.  
  800. /* Does the patch pattern match at line base+offset? */
  801.  
  802. bool
  803. patch_match(base, offset, fuzz)
  804. LINENUM base;
  805. LINENUM offset;
  806. LINENUM fuzz;
  807. {
  808.     Reg1 LINENUM pline = 1 + fuzz;
  809.     Reg2 LINENUM iline;
  810.     Reg3 LINENUM pat_lines = pch_ptrn_lines() - fuzz;
  811.  
  812.     for (iline=base+offset+fuzz; pline <= pat_lines; pline++,iline++) {
  813.     if (canonicalize) {
  814.         if (!similar(ifetch(iline, (offset >= 0)),
  815.              pfetch(pline),
  816.              pch_line_len(pline) ))
  817.         return FALSE;
  818.     }
  819.     else if (strnNE(ifetch(iline, (offset >= 0)),
  820.            pfetch(pline),
  821.            pch_line_len(pline) ))
  822.         return FALSE;
  823.     }
  824.     return TRUE;
  825. }
  826.  
  827. /* Do two lines match with canonicalized white space? */
  828.  
  829. bool
  830. similar(a,b,len)
  831. Reg1 char *a;
  832. Reg2 char *b;
  833. Reg3 int len;
  834. {
  835.     while (len) {
  836.     if (isspace(*b)) {        /* whitespace (or \n) to match? */
  837.         if (!isspace(*a))        /* no corresponding whitespace? */
  838.         return FALSE;
  839.         while (len && isspace(*b) && *b != '\n')
  840.         b++,len--;        /* skip pattern whitespace */
  841.         while (isspace(*a) && *a != '\n')
  842.         a++;            /* skip target whitespace */
  843.         if (*a == '\n' || *b == '\n')
  844.         return (*a == *b);    /* should end in sync */
  845.     }
  846.     else if (*a++ != *b++)        /* match non-whitespace chars */
  847.         return FALSE;
  848.     else
  849.         len--;            /* probably not necessary */
  850.     }
  851.     return TRUE;            /* actually, this is not reached */
  852.                     /* since there is always a \n */
  853. }
  854.  
  855. /* Exit with cleanup. */
  856.  
  857. void
  858. my_exit(status)
  859. int status;
  860. {
  861.     Unlink(TMPINNAME);
  862.     if (!toutkeep) {
  863.     Unlink(TMPOUTNAME);
  864.     }
  865.     if (!trejkeep) {
  866.     Unlink(TMPREJNAME);
  867.     }
  868.     Unlink(TMPPATNAME);
  869.     exit(status);
  870. }
  871.